﻿using System.Reflection;
using Autofac;

using System.Web.Mvc;
using Autofac.Integration.WebApi;
using System.Web.Http;
using Autofac.Integration.Mvc;
using Pay.Core;
using Pay.Service;
using Pay.IService;
using System.Linq;
using Pay.Token.Utils;
using Pay.TO;

namespace Pay.Token {
    /// <summary>
    /// 依赖注入[DI]
    /// </summary>
    public class DependencyInjectionConfig {
		/// <summary>
		///注册依赖注入
		/// </summary>
		public static void Register() {
			var builder = new ContainerBuilder();
			//注册api容器的实现
			builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
			//注册mvc容器的实现
			builder.RegisterControllers(Assembly.GetExecutingAssembly());
            builder.RegisterType<Repository>().As<IUnitOfWork>().InstancePerLifetimeScope();
            builder.RegisterType<OrderModelCacheService>().As<IOrderModelCache>();
            builder.RegisterAssemblyTypes(new Assembly[] { Assembly.Load("Pay.IService"), Assembly.Load("Pay.Service") })
                .Where(c => !c.GetInterfaces().Any(i => i.Name == "IUnitOfWork"))
                .AsImplementedInterfaces();
            builder.RegisterType<TokenUserDistribution>().Keyed<IDistribution>(UserType.user);
            builder.RegisterType<TokenMakerDistribution>().Keyed<IDistribution>(UserType.tokenMaker);
            builder.RegisterType<TokenNodeMallDistribution>().Keyed<IDistribution>(UserType.tokenNodeMall);
            builder.RegisterType<TokenCountyAgentDistribution>().Keyed<IDistribution>(UserType.tokenCountyAgent);
            builder.RegisterType<TokenCityAgentDistribution>().Keyed<IDistribution>(UserType.tokenCityAgent);
            builder.RegisterType<TokenMakerUpDistribution>().Keyed<IUpDistribution>(UserType.tokenMaker);
            //注册日志
            string[] log_names = new string[] { "data_change", "sql_info", "data_error", "ui_error", "info" };
			foreach (var log_name in log_names)
				builder.Register<ILogHelper>(c => new LogHelper(log_name)).Named<ILogHelper>(log_name).SingleInstance();

			//在Autofac中注册Redis的连接，并设置为Singleton (官方建議保留Connection，重複使用)
			//builder.Register(r =>{ return ConnectionMultiplexer.Connect(DBSetting.Redis);}).AsSelf().SingleInstance();
			var container = builder.Build();
            IocHelper.InitializeWith(container);
            //注册api容器需要使用HttpConfiguration对象
            GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);
			//注册MVC容器
			DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
		}
	}
}